const fs = require('fs');
const path = require('path');
const { log } = require('../../log');

/**
 * 创建map函数
 * @param {*} appPath
 */
function createMap(appPath) {
  log("开始 map 文件拷贝");
  mapSync(appPath, (filePath, fileName) => {
    try {
      const ollFile = path.join(filePath, fileName);
      const newFilePath = path.join(filePath.replace(/\\0\\/, "\\1\\").replace('/0/', "/1/"));
      if (fileName.indexOf('.js.map') > -1 || fileName.indexOf('.css.map') > -1) {
        if (!fs.existsSync(newFilePath)) {
          fs.mkdirSync(newFilePath, {
            recursive: true
          });
        }
        const fileData = fs.readFileSync(ollFile);
        fs.writeFileSync(path.join(newFilePath, fileName), fileData);
        fs.unlinkSync(ollFile);
      }
    } catch (error) {
      log("map文件拷贝异常", error);
    }
  });
  log("结束 map 文件拷贝");
}


/**
 * 递归调用
 * @param {*} currentDirPath
 * @param {*} callback
 */
function mapSync(currentDirPath, callback) {
  let listFile = [];
  try {
    listFile = fs.readdirSync(currentDirPath, {
      withFileTypes: true
    }) || [];
  } catch (error) {
    listFile = [];
    log("目录读取异常", error);
  }
  listFile.forEach((dirent) => {
    const filePath = path.join(currentDirPath, dirent.name);
    if (dirent.isFile()) {
      callback(path.join(currentDirPath), dirent.name);
    } else if (dirent.isDirectory()) {
      mapSync(filePath, callback);
    }
  });
}

module.exports = {
  createMap
}